import React, { useEffect, useMemo, useRef, useState } from "react";
import "../assets/sass/create_template/create_template.css";
import Header from "../component/CreateTemplate/Header";
import {
  AreaChartOutlined,
  ShakeOutlined,
  SignatureOutlined,
  FontColorsOutlined,
  UserOutlined,
  InfoCircleFilled,
  StepBackwardOutlined,
  StepForwardOutlined,
  CaretRightOutlined,
  CopyOutlined,
  LockOutlined,
  JavaScriptOutlined,
  ClusterOutlined,
  TableOutlined,
  MobileOutlined,
  PlusOutlined,
  QuestionCircleOutlined,
  MinusOutlined,
} from "@ant-design/icons";
import ToolCha from "../assets/image/create_template/tool/tool_cha.svg";
import { useDispatch, useSelector } from "react-redux";
import { componentsData } from "../data/tmp";
import { addItem, setCurrItemId } from "../store";
import Parent from "../component/CreateTemplate/Parent";
import { editorCpt } from "../component/CreateTemplate/TypeTmp/TypeTmp";
import { ColorPicker, Input, Slider, Tooltip } from "antd";
import type { ColorPickerProps, GetProp } from "antd";
import Draggable from "react-draggable";
import RightClick from "../component/CreateTemplate/TmpTool/RightClick";
import ComponentSettings from "../component/CreateTemplate/TmpTool/ComponentSettings";

type Color = GetProp<ColorPickerProps, "value">;

const CreateTemplate = () => {
  //左侧可伸缩tab
  const [templateBoxShow, setTemplateBoxShow] = useState(true);

  //左侧可伸缩tab默认高亮
  const [tabIndex, setTabIndex] = useState(0);

  //左侧可伸缩tab
  const tabItem = [
    {
      key: "Graphic",
      icon: <AreaChartOutlined className="icon" />,
      text: "图文",
    },
    {
      key: "Single_pager",
      icon: <ShakeOutlined className="icon" />,
      text: "单页",
    },
    {
      key: "ornament",
      icon: <SignatureOutlined className="icon" />,
      text: "装饰",
    },
    {
      key: "word_art",
      icon: <FontColorsOutlined className="icon" />,
      text: "艺术字",
    },
    {
      key: "mine",
      icon: <UserOutlined className="icon" />,
      text: "我的",
    },
  ];

  //左侧可伸缩tab点击
  const typeTab = (index: number) => {
    const doms: any = document.querySelector(".type_tab");
    if (doms.childNodes[index].classList[1]) {
      if (templateBoxShow === true) {
        tmpClose();
        setTemplateBoxShow(false);
        setTabIndex(-1);
      } else {
        tmpOpen();
        setTemplateBoxShow(true);
      }
    } else {
      setTabIndex(index);
      tmpOpen();
      setTemplateBoxShow(true);
    }
  };

  //左侧tab伸长
  function tmpOpen() {
    const template_box: any = document.querySelector(".template_box");
    const tab_box: any = document.querySelector(".tab");
    tab_box.style.display = "block";
    template_box.style.transition = 0.5 + "s";
    template_box.style.width = 1.875 + "rem";
  }
  //左侧tab收缩
  function tmpClose() {
    const template_box: any = document.querySelector(".template_box");
    const tab_box: any = document.querySelector(".tab");
    tab_box.style.display = "none";
    template_box.style.transition = 0.5 + "s";
    template_box.style.width = 0 + "px";
  }

  const dispatch = useDispatch();
  //拖动到画布上的物料数组
  const componentList = useSelector((state: any) => state.componentList);
  const [tmpIndex, setTmpIndex] = useState(null);
  const box = useRef(null);

  const onDragStart = (e: number) => {
    // 将数据存储在拖拽操作的数据中传输对象
    setTmpIndex(e);
  };
  // 处理拖放操作
  const onDrop = (e: { clientX: number; clientY: number }) => {
    // 获取box引用指向的DOM元素的位置信息，存储在变量a中
    const asty = box.current.getBoundingClientRect();
    // 鼠标相对于box元素左上角的偏移量，分别存储在变量lefts和变量tops中
    const lefts = e.clientX - asty.left;
    const tops = e.clientY - asty.top;
    // 数据传输对象中获取之前存储的索引数据，其存储在变量index中
    // 从componentsData数组中获取特定索引的数据，用深拷贝的方式创建了一个新的对象bnew
    const bnew = JSON.parse(JSON.stringify(componentsData[tmpIndex]));
    // 拖放后的新位置
    bnew.style = { ...bnew.style, left: lefts, top: tops };
    bnew.id = new Date().getTime();
    // dispath函数将更新后的bnew对象分发到Redux store中，以触发相应的状态更新
    dispatch(addItem(bnew));
  };

  const onDragOver = (e: { preventDefault: () => void }) => {
    e.preventDefault();
  };

  //右侧tab
  const [toolTabIndex, setToolTabIndex] = useState(0);

  //更改右侧tab
  const toolTabList = [
    {
      title: "页面设置",
    },
    {
      title: "图层管理",
    },
    {
      title: "页面管理",
    },
  ];

  const toolTab = (index: React.SetStateAction<number>) => {
    setToolTabIndex(index);
  };

  //更改背景色类型
  const [changeBgcTypeIndex, setChangeBgcType] = useState(0);
  const BgcType = ["纯色", "渐变"];
  const changeBgcType = (index) => {
    setChangeBgcType(index);
  };

  //背景色
  const bgcList = [
    {
      color: "#000000",
    },
    {
      color: "#FFFFFF",
      border: "1px solid #D8D8D8",
    },
    {
      color: "#E2E2E2",
    },
    {
      color: "#C35353",
    },
    {
      color: "#A02810",
    },
    {
      color: "#F7E1B7",
    },
    {
      color: "#E5B068",
    },
    {
      color: "#5E8C7D",
    },
    {
      color: "#183F3F",
    },
    {
      color: "#3774EE",
    },
    {
      color: "#5F63E0",
    },
    {
      color: "#33416D",
    },
  ];

  //初始背景色
  const [color, setColor] = useState<Color>("#ffffff");

  const bgColor = useMemo<string>(
    () => (typeof color === "string" ? color : color!.toHexString()),
    [color]
  );

  const btnStyle: React.CSSProperties = {
    backgroundColor: bgColor,
  };

  //更改背景色
  const changeBgc = (index: number) => {
    setBeforBgc("transparent");
    setBgcEd("transparent");
    setColor(bgcList[index].color);
  };

  //透明背景色
  const bgcTeansparent = () => {
    setColor("white");
  };

  //渐变色
  const gradienBgcList = [
    {
      angle: 0,
      beforBgc: "#5B5B5B",
      bgcEd: "#0A0A0A",
    },
    {
      angle: 0,
      beforBgc: "#F6F6F6",
      bgcEd: "#DCDCDC",
    },
    {
      angle: 0,
      beforBgc: "#E95E44",
      bgcEd: "#A81D09",
    },
    {
      angle: 0,
      beforBgc: "#F4D87E",
      bgcEd: "#F49054",
    },
    {
      angle: 0,
      beforBgc: "#FBDBB2",
      bgcEd: "#E5B06B",
    },
    {
      angle: 0,
      beforBgc: "#FCD4A0",
      bgcEd: "#DD9C49",
    },
    {
      angle: 0,
      beforBgc: "#B1EEF7",
      bgcEd: "#44BCC4",
    },
    {
      angle: 0,
      beforBgc: "#85E7CF",
      bgcEd: "#15869B",
    },
    {
      angle: 0,
      beforBgc: "#BD88D8",
      bgcEd: "#8C6CAC",
    },
    {
      angle: 0,
      beforBgc: "#82507D",
      bgcEd: "#4E4555",
    },
    {
      angle: 0,
      beforBgc: "#85C6FD",
      bgcEd: "#3787EE",
    },
    {
      angle: 0,
      beforBgc: "#6598E0",
      bgcEd: "#5853C8",
    },
    {
      angle: 0,
      beforBgc: "#6D6D86",
      bgcEd: "#323244",
    },
  ];

  //渐变角度
  const [bgcAngle, setBgcAngle] = useState(0);
  //开始渐变颜色
  const [beforBgc, setBeforBgc] = useState(null);
  //结束渐变颜色
  const [bgcEd, setBgcEd] = useState(null);

  //更改渐变色
  const changeGradienBgc = (index: number) => {
    setBeforBgc(gradienBgcList[index].beforBgc);
    setBgcEd(gradienBgcList[index].bgcEd);
  };

  // 渐变色透明
  const gradienBgcTeansparent = () => {
    setBeforBgc("transparent");
    setBgcEd("transparent");
  };

  // 进度条改变渐变色角度
  const changeSilder = (value: React.SetStateAction<number>) => {
    setBgcAngle(value);
  };

  //输入更改渐变角度
  const changeTextAngle = (e) => {
    if (e.target.innerHTML > 360 && e.target.innerHTML.length >= 3) {
      setBgcAngle(360);
      e.target.innerHTML = 360;
    } else {
      setBgcAngle(e.target.innerHTML);
    }
  };

  //更改背景图片类型
  const [changeBgcImageTypeIndex, setChangeBgcImageType] = useState(0);
  const BgcImageType = ["图片", "纹理"];
  const changeBgcImageType = (index) => {
    setChangeBgcImageType(index);
  };

  //添加图片
  const [imgBoxShow, setImgBoxShow] = useState(false);
  const add_image = () => {
    setImgBoxShow(true);
  };

  //画布尺寸
  const [screenSize, setScreenSize] = useState(1);

  const addSIze = () => {
    setScreenSize(screenSize + 0.25);
    if (screenSize >= 2) {
      setScreenSize(2);
    }
  };
  const subSize = () => {
    setScreenSize(screenSize - 0.25);
    if (screenSize <= 0.5) {
      setScreenSize(0.5);
    }
  };

  //是否显示手机
  const [showPhone, setShowPhone] = useState(false);
  const changePhone = () => {
    if (showPhone === true) {
      setShowPhone(false);
    } else {
      setShowPhone(true);
    }
  };

  //右键菜单
  const menuInfo = useSelector((state: any) => state.menuInfo);

  //左侧我的切换
  const tabTopList = ["推荐", "收藏", "已购"];
  const [tabTopIndex, setTabTopIndex] = useState(0);
  const changeTabTop = (index) => {
    setTabTopIndex(index);
  };

  //获取ID判断是否获取焦点显示组件设置
  const cId = useSelector((state: any) => state.currentCptId);
  const [showSettings, setShowSettings] = useState(false);
  useEffect(() => {
    (async () => {
      if (cId) {
        setShowSettings(true);
      } else {
        setShowSettings(false);
      }
    })();
  }, [cId]);

  //没有触焦的组件时ID设成空
  const editAreaClikc = (e) => {
    if (e.target.className === "edid_area") {
      dispatch(setCurrItemId(null));
    }
  };

  return (
    <div className="create_template_page">
      <Header
        imgBoxShow={imgBoxShow}
        closeImgBox={() => setImgBoxShow(false)}
      ></Header>
      {/* 组件设置 */}

      <div className="main">
        {/* 组件设置 */}
        {showSettings && (
          <Draggable
            bounds={{ top: 0, bottom: 50 }}
            handle={".component_settings_box"}
          >
            <div className="component_settings_box">
              <ComponentSettings
                click={() => setShowSettings(false)}
              ></ComponentSettings>
            </div>
          </Draggable>
        )}

        {/* 左侧可收缩tab栏 */}
        <div className="tab_type">
          <div className="type_tab">
            {tabItem &&
              tabItem.map((item, index) => {
                return (
                  <div
                    className={
                      tabIndex === index
                        ? "type_item type_item_hover"
                        : "type_item"
                    }
                    key={index}
                    onClick={() => typeTab(index)}
                  >
                    {item.icon}
                    <span className="text">{item.text}</span>
                  </div>
                );
              })}
          </div>
          <div className="help_box">
            <div className="api">API对接</div>
            <div className="help">
              <InfoCircleFilled className="icon" />
              <div className="text">帮助</div>
              <div className="help_popup">
                <div>帮助中心</div>
                <div>客服</div>
                <div>反馈</div>
                <div>秒懂H5</div>
              </div>
            </div>
          </div>
        </div>
        <div className="template_box">
          <div className="tab">
            <div className="tab_top">
              {tabTopList &&
                tabTopList.map((item, index) => {
                  return (
                    //左侧我的tab切换
                    <div
                      className={
                        tabTopIndex === index
                          ? "tab_top_item tab_top_item_active"
                          : "tab_top_item"
                      }
                      key={index}
                      onClick={() => changeTabTop(index)}
                    >
                      {item}
                    </div>
                  );
                })}
            </div>
            {/* 推荐模板 */}
            {tabTopIndex === 0 &&
              componentsData.map((item, index) => {
                return (
                  <div
                    className="tab_item"
                    key={index}
                    draggable
                    onDragStart={() => onDragStart(index)}
                  >
                    <span>{item.lable}</span>
                  </div>
                );
              })}
            {/* 已购模板 */}
            {tabTopIndex === 1 && (
              <div className="collection">
                <div className="box">
                  <img src="/src/assets/image/create_template/no_collection.png" />
                  <span>还没有收藏模板</span>
                </div>
              </div>
            )}
            {/* 已购模板 */}
            {tabTopIndex === 2 && (
              <div className="buy">
                <div className="box">
                  <img src="/src/assets/image/create_template/no_buy.png" />
                  <span>还没有已购模板</span>
                </div>
              </div>
            )}
          </div>
        </div>
        {/* 中间区域 */}
        <div className="workspace">
          {/* 画布 */}
          <div
            className="edid_area"
            onDragOver={onDragOver}
            onContextMenu={(event) => event.preventDefault()}
            ref={box}
            onClick={editAreaClikc}
            onDrop={onDrop}
            style={{
              backgroundImage: `linear-gradient(${bgcAngle}deg,${beforBgc},${bgcEd})`,
              ...btnStyle,
              transform: `scale(${screenSize})`,
            }}
          >
            {componentList.length > 0 &&
              componentList.map((element: any, index: number) => {
                const Cpt = editorCpt[element.component];
                return (
                  <Parent {...element} key={index}>
                    {Cpt ? <Cpt {...element} /> : ""}
                  </Parent>
                );
              })}
            {/* 右键菜单栏 */}
            {menuInfo.showMenu && <RightClick></RightClick>}
            {showPhone ? (
              // 显示手机边框
              <div className="phone_page">
                <div className="phone_box"></div>
              </div>
            ) : (
              //常规屏/主流屏
              <div style={{ zIndex: "5", pointerEvents: "none" }}>
                <div className="mainstream_screens">
                  <Tooltip
                    placement="left"
                    color="white"
                    title={
                      <span id="Tooltitle">
                        640*1260px，包含但不限于iPhoneX/11/12113系列、OPPOR17等机型
                      </span>
                    }
                  >
                    主流屏
                    <QuestionCircleOutlined />
                  </Tooltip>
                </div>
                <div className="regular_screen">
                  <div className="text">
                    <Tooltip
                      placement="left"
                      color="white"
                      title={
                        <span id="Tooltitle">
                          640*972px，适配部分小屏机型，包含但不限于华为荣耀V8等带虚拟键机型123
                        </span>
                      }
                    >
                      常规屏 <QuestionCircleOutlined />
                    </Tooltip>
                  </div>
                </div>
              </div>
            )}
            <div className="change_page">长度太短?将其切换为长页面&gt;&gt;</div>
          </div>
        </div>
        <div className="tool">
          {/* 右侧工具栏 */}
          <div className="tool_box">
            {/* 撤销 */}
            <Tooltip placement="left" title={"撤消(ctrl+z)"}>
              <div className="back">
                <StepBackwardOutlined />
              </div>
            </Tooltip>
            {/* 恢复 */}
            <Tooltip placement="left" title={"恢复(ctrl+y)"}>
              <div className="prev">
                <StepForwardOutlined />
              </div>
            </Tooltip>
            {/* 刷新预览 */}
            <Tooltip placement="left" title={"刷新预览"}>
              <div className="start">
                <CaretRightOutlined />
              </div>
            </Tooltip>
            {/* 复制当前页 */}
            <div className="line"></div>
            <Tooltip placement="left" title={"复制当前页"}>
              <div className="copy_page">
                <CopyOutlined />
              </div>
            </Tooltip>
            {/* 上锁 */}
            <div className="lock">
              <LockOutlined />
            </div>
            {/* AI智能检测 */}
            <Tooltip placement="left" title={"AI智能检测"}>
              <div className="ai">
                <img src={ToolCha} alt="" />
              </div>
            </Tooltip>
            {/* 导入PSD */}
            <Tooltip placement="left" title={"导入PSD"}>
              <div className="PSD">
                <JavaScriptOutlined />
              </div>
            </Tooltip>
            {/* 快捷键 */}
            <Tooltip placement="left" title={"快捷键"}>
              <div className="shortcut_key">
                <ClusterOutlined />
              </div>
            </Tooltip>
            <div className="line"></div>
            {/* 网格设置 */}
            <Tooltip placement="left" title={"网格设置"}>
              <div className="grid">
                <TableOutlined />
              </div>
            </Tooltip>
            {/* 手机边框 */}
            <Tooltip placement="left" title={"手机边框"}>
              <div className="phone" onClick={changePhone}>
                <MobileOutlined />
              </div>
            </Tooltip>
            {/* 放大画布尺寸 */}
            <div className="add_size" onClick={addSIze}>
              <PlusOutlined />
            </div>
            {/* 画布尺寸百分比 */}
            <div className="screen_size">{screenSize * 100}%</div>
            {/* 缩小画布尺寸 */}
            <div className="subtract_size" onClick={subSize}>
              <MinusOutlined />
            </div>
          </div>
          <div className="tool_page_manage">
            {/* 画布设置栏tab */}
            <div className="tool_tab">
              {toolTabList &&
                toolTabList.map((item, index) => {
                  return (
                    <div
                      onClick={() => toolTab(index)}
                      key={index}
                      className={
                        toolTabIndex === index
                          ? "tool_tab_item tool_tab_item_active"
                          : "tool_tab_item"
                      }
                    >
                      {item.title}
                    </div>
                  );
                })}
            </div>
            {/* 画布设置栏 */}
            <div className="tool_tab_box">
              {toolTabIndex === 0 && (
                //页面设置
                <div className="page_setup">
                  {/* //背景颜色 */}
                  <div className="background_color">
                    <div className="bgc_change">
                      <div className="bgc_title">背景颜色</div>
                      <div className="bgc_switch">
                        {BgcType &&
                          BgcType.map((item, index) => {
                            return (
                              <div
                                onClick={() => changeBgcType(index)}
                                className={
                                  changeBgcTypeIndex === index ? "active" : ""
                                }
                                key={index}
                              >
                                {item}
                              </div>
                            );
                          })}
                      </div>
                    </div>
                    {/* //纯色背景色 */}
                    {changeBgcTypeIndex === 0 && (
                      <div className="bgc_box">
                        <ColorPicker
                          value={color}
                          onChange={setColor}
                          placement="top"
                          showText
                        >
                          <div className="bgc_box_item color_picker"></div>
                        </ColorPicker>
                        <div
                          className="bgc_box_item transparent_color"
                          onClick={bgcTeansparent}
                        ></div>
                        {bgcList &&
                          bgcList.map((item, index) => {
                            return (
                              <div
                                key={index}
                                onClick={() => changeBgc(index)}
                                className="bgc_box_item"
                                style={{
                                  background: item.color,
                                  border: item.border,
                                }}
                              ></div>
                            );
                          })}
                      </div>
                    )}
                    {/* //渐变背景色 */}
                    {changeBgcTypeIndex === 1 && (
                      <div className="gradien_bgc">
                        <div
                          className="show_bgc"
                          style={{
                            background: `linear-gradient(45deg,${beforBgc},${bgcEd})`,
                          }}
                        >
                          <div></div>
                          <div></div>
                        </div>
                        <div className="change_angle">
                          <div className="text">角度</div>
                          <div className="silder">
                            <Slider
                              defaultValue={0}
                              value={bgcAngle}
                              min={0}
                              max={360}
                              onChange={changeSilder}
                            />
                          </div>
                          <div
                            className="input_angle"
                            contentEditable
                            onInput={changeTextAngle}
                            suppressContentEditableWarning
                          >
                            {bgcAngle}
                          </div>
                        </div>
                        <div className="gradien_bgc_box">
                          <div
                            className="bgc_box_item transparent_color"
                            onClick={gradienBgcTeansparent}
                          ></div>
                          {gradienBgcList &&
                            gradienBgcList.map((item, index) => {
                              return (
                                <div
                                  className="bgc_box_item"
                                  key={index}
                                  onClick={() => changeGradienBgc(index)}
                                  style={{
                                    background: `linear-gradient(${item.angle}deg,${item.beforBgc},${item.bgcEd})`,
                                  }}
                                ></div>
                              );
                            })}
                        </div>
                      </div>
                    )}
                  </div>
                  {/* 背景叠加 */}
                  <div className="background_overlay">
                    <div className="bgc_change">
                      <div className="bgc_title">背景叠加</div>
                      <div className="bgc_switch">
                        {BgcImageType &&
                          BgcImageType.map((item, index) => {
                            return (
                              <div
                                onClick={() => changeBgcImageType(index)}
                                className={
                                  changeBgcImageTypeIndex === index
                                    ? "active"
                                    : ""
                                }
                                key={index}
                              >
                                {item}
                              </div>
                            );
                          })}
                      </div>
                    </div>
                    {/* 背景图片 */}
                    {changeBgcImageTypeIndex === 0 && (
                      <div className="add_image_box">
                        <div className="add_image" onClick={add_image}>
                          <div className="add_icon">+</div>
                          <div className="add_text">
                            为了在浏览作品时适配更多机型,推荐您使用背景功能
                          </div>
                        </div>
                        <div className="opacity">
                          <div className="text">透明度</div>
                          <Input
                            className="change_opacity"
                            // onChange={setOpacity}
                            suffix={
                              <Tooltip title="Extra information">
                                <span style={{ color: "#ABABAB" }}>%</span>
                              </Tooltip>
                            }
                          />
                        </div>
                        <div className="bgc_animation">
                          <div className="text">背景动画</div>
                          <div className="go_add">去添加&gt;</div>
                        </div>
                        <div className="bgc_all_page">背景应用于所有页面</div>
                      </div>
                    )}
                    {/* 背景纹理 */}
                    {changeBgcImageTypeIndex === 1 && (
                      <div className="add_texture_box"></div>
                    )}
                  </div>
                </div>
              )}
              {/* 图层管理 */}
              {toolTabIndex === 1 && (
                <div className="layer_management">图层管理</div>
              )}
              {/* 页面管理 */}
              {toolTabIndex === 2 && (
                <div className="page_management">页面管理</div>
              )}
            </div>
          </div>
          <div className="ai_aides">AI</div>
        </div>
      </div>
    </div>
  );
};

export default CreateTemplate;
